package com.nti56.springboot.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class TMSMessageUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(TMSMessageUtil.class);

	public static Properties plateNumberFromat;
	
	static{
		loadProps();
	}
	
	synchronized static private void loadProps() {
		InputStream in = null;
		try {
			in = Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/plateNumberFormat.properties");
			plateNumberFromat = new Properties();			
			plateNumberFromat.load(in);
		} catch (IOException e) {
			throw new RuntimeException("没有找到plateNumberFormat.properties或文件不可用");
		}finally {
            try {
                if(null != in) {
                    in.close();
                }
            } catch (IOException e) {
            	logger.error("plateNumberFormat.properties文件流关闭出现异常");
            }
        }
	} 
	
	public static String formatPlateNumber(String plateNumber){
		if(plateNumber ==null)
			return null;
		//过滤汉字的表达式
		String reg = "[^\u4e00-\u9fa5]";
		//车牌中的汉字
		String cn = plateNumber.replaceAll(reg, "");
		char [] cnArr = cn.toCharArray(); 
		for(char c : cnArr) {
			String key = String.valueOf(c);
			String replaceValue =  plateNumberFromat.getProperty(key);
			if(!StringUtil.isEmpty(replaceValue)){
				plateNumber = plateNumber.replace(key, replaceValue+"_");
			}
		}
		
		plateNumber = plateNumber.replace("挂", "_GUA");
		return plateNumber;
	}
	
	public static String parseFormatPlateNumber(String formatplateNumber){
		if(formatplateNumber ==null)
			return null;
		String value = formatplateNumber.substring(0,3);
		Set<Entry<Object, Object>> keyValue = plateNumberFromat.entrySet();
		for(Entry entry:keyValue){
			if(value.equalsIgnoreCase(entry.getValue().toString())){
				formatplateNumber = formatplateNumber.toUpperCase().replace(value, entry.getKey().toString());
				break;
			}
		}
		String plateNumber = formatplateNumber.toUpperCase().replace("_GUA","挂" );
		plateNumber = plateNumber.replace("_", "");
		return plateNumber;
	}
	
}
